package com.travel.travel_springboot_web.service;

import com.travel.travel_springboot_web.entity.Address;
import com.travel.travel_springboot_web.mapper.AddressMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressService {
    
    private static final Logger logger = LoggerFactory.getLogger(AddressService.class);
    
    @Autowired
    private AddressMapper addressMapper;
    
    @Transactional
    public Address createAddress(Address address) {
        try {
            // 1. 检查用户是否已有地址
            List<Address> existingAddresses = addressMapper.findByUserId(address.getUserId());
            logger.info("Found {} existing addresses for user {}", existingAddresses.size(), address.getUserId());
            
            if (!existingAddresses.isEmpty()) {
                // 2. 如果已有地址，更新现有地址
                Address existingAddress = existingAddresses.get(0);  // 获取第一个地址
                address.setId(existingAddress.getId());  // 设置ID以更新现有记录
                address.setIsDefault(1);  // 设为默认地址
                
                if (addressMapper.update(address) > 0) {
                    logger.info("Updated existing address: {}", existingAddress.getId());
                    return address;
                } else {
                    throw new RuntimeException("更新地址失败");
                }
            } else {
                // 3. 如果没有地址，创建新地址
                address.setIsDefault(1);  // 设为默认地址
                if (addressMapper.insert(address) > 0) {
                    logger.info("Created new address: {}", address.getId());
                    return address;
                } else {
                    throw new RuntimeException("创建地址失败");
                }
            }
        } catch (Exception e) {
            logger.error("Error creating/updating address: ", e);
            throw new RuntimeException("保存地址失败: " + e.getMessage());
        }
    }
    
    public List<Address> getAddressList(Long userId) {
        try {
            List<Address> addresses = addressMapper.findByUserId(userId);
            logger.info("Found {} addresses for user {}", addresses.size(), userId);
            return addresses;
        } catch (Exception e) {
            logger.error("Error getting address list: ", e);
            throw new RuntimeException("获取地址列表失败: " + e.getMessage());
        }
    }
    
    @Transactional
    public boolean updateAddress(Address address) {
        logger.info("Updating address: {}", address.getId());
        
        try {
            // 设为默认地址
            address.setIsDefault(1);
            return addressMapper.update(address) > 0;
        } catch (Exception e) {
            logger.error("Error updating address: ", e);
            throw new RuntimeException("Failed to update address: " + e.getMessage());
        }
    }
    
    public boolean deleteAddress(Long id, Long userId) {
        logger.info("Deleting address: {} for user: {}", id, userId);
        return addressMapper.delete(id, userId) > 0;
    }
} 